package com.example.assetmanagement.service.impl;

import com.example.assetmanagement.service.AttachmentService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class AttachmentServiceImpl implements AttachmentService {

    @Value("${upload.dir:uploads}")
    private String uploadDir;

    @Override
    public String upload(MultipartFile file, String bizType) throws IOException {
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String dateDir = LocalDate.now().toString();
        Path dir = Paths.get(uploadDir, bizType == null ? "common" : bizType, dateDir);
        Files.createDirectories(dir);
        String filename = UUID.randomUUID().toString().replace("-", "") + (ext.isEmpty() ? "" : "." + ext);
        Path target = dir.resolve(filename);
        file.transferTo(target);
        // 返回相对路径
        return "/files/" + bizType + "/" + dateDir + "/" + filename;
    }

    @Override
    public byte[] download(String relativePath) throws IOException {
        Path path = Paths.get(uploadDir).resolve(relativePath);
        return Files.readAllBytes(path);
    }

    @Override
    public void delete(String relativePath) throws IOException {
        Path path = Paths.get(uploadDir).resolve(relativePath);
        FileSystemUtils.deleteRecursively(path);
    }
} 